<template>
  <view class="category">
    <scroll-view
      scroll-y
      style="height: 100%"
      id="scrollView"
      :scroll-into-view="scrollIntoViewId"
      scroll-with-animation
    >
      <view class="category-list">
        <view
          class="category-item"
          v-for="(item, index) in list"
          :key="item.id"
          :id="'category-' + item.id"
          :class="currentCategoryId === item.id ? 'active' : ''"
          @click="handleCategoryClick(index)"
        >
          <u-text
            :text="item.name"
            :lines="1"
            :color="currentCategoryId == item.id ? '5ae372' : '#333'"
            :size="14"
          ></u-text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref } from "vue";

const currentCategoryId = defineModel({ type: [Number, String] });

const props = defineProps({
  list: {
    type: Array,
    default: () => [],
  },
});

const scrollIntoViewId = ref("");

const handleCategoryClick = (index) => {
  // 计算要滚动到的类目索引，隔一个类目距离
  const targetIndex = index < 1 ? 0 : index - 1;
  const prevItem = props.list[targetIndex];
  const targetItem = props.list[index];
  scrollIntoViewId.value = `category-${prevItem.id}`;
  currentCategoryId.value = targetItem.id;
};
</script>

<style lang="scss" scoped>
.category {
  background-color: #f7f7f7;
  box-sizing: border-box;
  width: 110px;
  height: 100%;

  .category-list {
    .category-item {
      padding: 15px 10px;
      font-size: 14px;
      color: #333;
      position: relative;

      &.active {
        background-color: #fff;
        color: $u-primary;
        &::before {
          content: "";
          display: block;
          position: absolute;
          left: 0;
          top: 0;
          width: 5px;
          height: 100%;
          background-color: $u-primary;
        }
      }
    }
  }
}
</style>
